// src/stores/userStore.js
import { defineStore } from 'pinia'
import { login, logout } from '@/api/auth'
import { apiClient } from '@/api/base'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem('token') || '',
    userId: localStorage.getItem('userId') || '',       // 对应 SysUser.id
    username: localStorage.getItem('username') || '',   // 对应 SysUser.username
    nickname: localStorage.getItem('nickname') || '',   // 对应 SysUser.nickname
    permissions: safelyParseJSON(localStorage.getItem('permissions')) || [],
    roles: safelyParseJSON(localStorage.getItem('roles')) || [],
    status: localStorage.getItem('status') || 1,        // 对应 SysUser.status
    lastActivityTime: localStorage.getItem('lastActivityTime') || Date.now() // 最后活动时间
  }),

  actions: {
    // 同步设置Token
    setToken(newToken) {
      this.token = newToken
      localStorage.setItem('token', newToken)
    },

    // 同步用户信息（适配新字段）
    setUserInfo({ id, username, nickname, permissions, roles, status }) {
      this.userId = id
      this.username = username
      this.nickname = nickname
      this.permissions = permissions
      this.roles = roles
      this.status = status
      
      localStorage.setItem('userId', String(id)); 
      localStorage.setItem('username', username)
      localStorage.setItem('nickname', nickname)
      localStorage.setItem('permissions', JSON.stringify(permissions))
      localStorage.setItem('roles', JSON.stringify(roles))
      localStorage.setItem('status', status)
    },

    // 修改后的登录方法
    async login(loginData) {
      try {
        const response = await login(loginData)
        this.setToken(response.token)
        this.setUserInfo({
          id: response.userId,          // 确保后端返回包含userId
          username: loginData.username,
          nickname: response.nickname,  // 对应后端返回的nickname字段
          permissions: response.permissions,
          roles: response.roles,
          status: response.status || 1
        })
        return true
      } catch (error) {
        console.error('登录失败', error)
        throw error
      }
    },

    // 登出方法保持不变
    logout() {
      logout()
      this.$reset()
      localStorage.clear()
    },

    // 更新最后活动时间
    updateLastActivityTime() {
      this.lastActivityTime = Date.now()
      localStorage.setItem('lastActivityTime', this.lastActivityTime.toString())
    }
  },

  getters: {
    // 检查是否为超级管理员
    isAdmin: (state) => {
      return (state.roles && state.roles.includes('ROLE_ADMIN')) || 
             (state.permissions && state.permissions.includes('ROLE_ADMIN'))
    },

    // 权限检查 - 支持超级管理员
    hasPermission: (state) => (required) => {
      if (!required) return true
      
      // 超级管理员拥有所有权限
      if ((state.roles && state.roles.includes('ROLE_ADMIN')) || 
          (state.permissions && state.permissions.includes('ROLE_ADMIN'))) {
        return true
      }
      
      return state.permissions && state.permissions.includes(required)
    },

    // 多权限检查 - 支持超级管理员
    hasAnyPermission: (state) => (permissions) => {
      if (!permissions || permissions.length === 0) return true
      
      // 超级管理员拥有所有权限
      if ((state.roles && state.roles.includes('ROLE_ADMIN')) || 
          (state.permissions && state.permissions.includes('ROLE_ADMIN'))) {
        return true
      }
      
      return permissions.some(p => state.permissions && state.permissions.includes(p))
    },

    // 登录状态
    isLoggedIn: (state) => !!state.token,

    // 新增用户状态检查
    isActive: (state) => state.status === 1
  }
})

// 安全解析JSON
function safelyParseJSON(value) {
  try {
    return value ? JSON.parse(value) : null
  } catch (error) {
    console.error('JSON 解析失败:', error)
    return null
  }
}